package com.tiankun.eurekasellgoods.controller;



import com.tiankun.eurekasellgoods.Utils.JsonResult;
import com.tiankun.eurekasellgoods.exception.BusinessException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/uploadGoods")
public class uploadController {

    @PostMapping(value = "/uploadImg")
    public Map<String,Object> tempUpload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        if (multipartFile.isEmpty()){
            throw new BusinessException("空文件不能上传");

        }
        if (multipartFile.getSize()>1024*1024){
            throw new BusinessException("不能大于1m");
        }
        String originalFilename = multipartFile.getOriginalFilename();
        // 从原始文件名中获取后缀,作为新添加的文件的文件名后缀(匹配) hz
        String hz = originalFilename.substring(originalFilename.indexOf(".")+1);
        //后缀必须是png/jpg/jpeg/gif！！！
        if (!hz.equals("png") && !hz.equals("jpg") && !hz.equals("jpeg") && !hz.equals("gif")){
            throw new BusinessException("图片类型不正确");
        }

        //产生临时文件名
        String targetFile = UUID.randomUUID().toString().replace("-","")+"."+hz;
        String fileName="/usr/upload/img/"+targetFile;
        String fileName2="http://106.14.39.205:8770/tiankun-api-sellgoods/img/"+targetFile;
//         docker run -p 8085:8085 -v /usr/upload/img/:/usr/upload/img/  --name test -d test
//        -v /usr/upload/img/:/usr/upload/img/
//        http://106.14.39.205:8770/tiankun-api-admin/img/1648e62e1c274aa7adf8ec9bda63c875.jpg
//        String fileName="/usr/upload/chenhui/img/"+targetFile;

        //当项目挂载到服务器时存储图片
//        通过目标（虚拟）路径和服务其中的真实路径进行映射
        //服务器中设置虚拟路径

//        // 构建文件对象
        File uploadFile = new File(fileName);
        try {
            multipartFile.transferTo(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        String tempPath="http://106.14.39.205:8080/usr/upload/chenhui/img/"+targetFile;
//        return ResultModel.success("文件上传成功",tempPath);
        JsonResult jsonResult =new JsonResult();
        jsonResult.setCode("1");
        jsonResult.put("fileName",targetFile);
        jsonResult.setData(fileName2);

        return jsonResult.getValues();
    }


//    @PostMapping(value = "/cancelUpload")
//    public Map cancelUpload(@RequestBody Map<String,String> map){
//        String path="G:\\git\\image\\"+map.get("img");
//        File file=new File(path);
//        if (file.isFile() && file.exists()){
//            System.out.println(2);
//            file.delete();
//        }
//        return ResultModel.success("删除成功");
//    }

}
